const path = require("path");
const fs = require("fs");

/**
 * 读取文件
 * @param {*} dir
 * @param {*} fileList
 * @returns
 */
function listFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  //console.log(files);
  files.forEach((item) => {
    var fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    if (!stat.isDirectory()) {
      fileList.push(fullPath);
    }
  });
  return fileList;
}

/**
 * 读取文件夹
 * @param {*} dir
 * @param {*} fileList
 * @returns
 */
function listDirs(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  //console.log(files);
  files.forEach((item) => {
    var fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      fileList.push(fullPath);
    }
  });
  return fileList;
}

/**
 * 递归读取文件
 * @param {*} dir
 * @param {*} fileList
 * @returns
 */
function loopFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  //console.log(files);
  files.forEach((item) => {
    var fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      loopFiles(path.join(dir, item), fileList); //递归读取文件
    } else {
      fileList.push(fullPath);
    }
  });
  return fileList;
}

// /**
//  * 写文件内容
//  * @param {*} filePath
//  * @param {*} text
//  */
// function writeFile(dir, fileName, fileText) {
//   fs.mkdirSync(dir, { recursive: true });

//   const data = new Uint8Array(Buffer.from(fileText));

//   fs.writeFileSync(`${dir}/${fileName}`, data, "utf8");
// }

/**
 * 写文件
 * @param {*} filePath
 * @param {*} fileInfo
 */
function writeFile(filePath, fileInfo) {
  var dir = path.dirname(filePath);

  fs.mkdirSync(dir, { recursive: true });

  const data = new Uint8Array(Buffer.from(fileInfo));

  fs.writeFileSync(filePath, data, "utf8");
}

/**
 * 读文件
 * @param {*} filePath
 * @param {*} fileInfo
 */
function readFile(filePath) {
  var data = fs.readFileSync(filePath, "utf8");

  return data;
}

let FileHelper = {
  listFiles,
  listDirs,
  loopFiles,
  writeFile,
  readFile,
};

export default FileHelper;
